﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using StudentLookup.Resources;
using HtmlAgilityPack;
using StudentLookup.BaseEntity;
using System.Net.Http;
using StudentLookup.Utilities;
using System.Collections;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Linq;
using System.Xml.Serialization;
using System.IO.IsolatedStorage;
using System.IO;

namespace StudentLookup
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();

            // Sample code to localize the ApplicationBar
            //BuildLocalizedApplicationBar();
        }

        // Sample code for building a localized ApplicationBar
        //private void BuildLocalizedApplicationBar()
        //{
        //    // Set the page's ApplicationBar to a new instance of ApplicationBar.
        //    ApplicationBar = new ApplicationBar();

        //    // Create a new button and set the text value to the localized string from AppResources.
        //    ApplicationBarIconButton appBarButton = new ApplicationBarIconButton(new Uri("/Assets/AppBar/appbar.add.rest.png", UriKind.Relative));
        //    appBarButton.Text = AppResources.AppBarButtonText;
        //    ApplicationBar.Buttons.Add(appBarButton);

        //    // Create a new menu item with the localized string from AppResources.
        //    ApplicationBarMenuItem appBarMenuItem = new ApplicationBarMenuItem(AppResources.AppBarMenuItemText);
        //    ApplicationBar.MenuItems.Add(appBarMenuItem);
        //}

        private async void btnSeachSchedule(object sender, RoutedEventArgs e)
        {
            if (txtStudentId.Text != "")
            {
                Student student = new Student();
                student.StudentId = txtStudentId.Text;
                string htmlPage = "";
                try
                {
                    using (var client = new HttpClient())
                    {
                        htmlPage = await client.GetStringAsync(Constant.URL_ScheduleExam + student.StudentId);
                    }

                    HtmlDocument htmlDocument = new HtmlDocument();
                    htmlDocument.LoadHtml(htmlPage);
                    //Hiển thị thông tin sv
                    HtmlNode studentName = htmlDocument.DocumentNode.SelectSingleNode("//*[@id=\"_ctl8_viewResult\"]/div/div/div/table//tr[1]/td[2]/strong/text()");
                    HtmlNode studentId = htmlDocument.DocumentNode.SelectSingleNode("//*[@id=\"_ctl8_viewResult\"]/div/div/div/table//tr[2]/td[2]/strong/text()");
                    HtmlNode studentStable = htmlDocument.DocumentNode.SelectSingleNode("//*[@id=\"_ctl8_viewResult\"]/div/div/div/table//tr[3]/td[2]/strong/text()");

                    txtStudentName.Text = Library.RemoveSpecialCharacter(studentName.InnerText.Trim());
                    txtStudentCode.Text = txtStudentId.Text;
                    txtClassStable.Text = studentStable.InnerText.Trim();

                    //Hiển thị danh sách môn thi
                    List<ScheduleExamination> listSchedule = new List<ScheduleExamination>();
                    foreach (var divTag in htmlDocument.DocumentNode.SelectNodes("//tr[@class='kTableRow'] | //tr[@class='kTableAltRow']"))
                    {
                        ScheduleExamination scheduleExam = new ScheduleExamination();
                        string courseName = (divTag.SelectSingleNode(".//td[2]").InnerText.Trim());
                        scheduleExam.CourseName = Library.LimitWords(courseName, 7, " ...");
                        string dayOf = divTag.SelectSingleNode(".//td[3]").InnerText.Trim();
                        string date = divTag.SelectSingleNode(".//td[4]").InnerText.Trim();
                        scheduleExam.ScheduleExamDate = dayOf + " " + date;

                        listSchedule.Add(scheduleExam);
                    }
                    listScheduleExam.ItemsSource = listSchedule;
                }
                catch (HttpRequestException)
                {
                    MessageBox.Show("Error: HttpRequest");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            else
            {
                MessageBox.Show("Bạn chưa nhập mã sinh viên.");
            }
        }

        private void listScheduleExam_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/UserControl/ScheduleDetail.xaml?indexSelected=" + listScheduleExam.SelectedIndex + "&studentId=" + txtStudentId.Text, UriKind.RelativeOrAbsolute));
        }

        private async void btnSearchResultTest(object sender, RoutedEventArgs e)
        {
            if (txtStudentIdResultTest.Text != "")
            {
                Student student = new Student();
                student.StudentId = txtStudentIdResultTest.Text;
                string htmlPage = "";
                try
                {
                    using (var client = new HttpClient())
                    {
                        htmlPage = await client.GetStringAsync(Constant.URL_ResultTest + student.StudentId);
                    }

                    HtmlDocument htmlDocument = new HtmlDocument();
                    htmlDocument.LoadHtml(htmlPage);
                    HtmlNode studentName = htmlDocument.DocumentNode.SelectSingleNode("//*[@id=\"_ctl8_viewResult\"]/div/div/div/table//tr[1]/td[2]/strong/text()");
                    HtmlNode studentId = htmlDocument.DocumentNode.SelectSingleNode("//*[@id=\"_ctl8_viewResult\"]/div/div/div/table//tr[2]/td[2]/strong/text()");
                    HtmlNode studentStable = htmlDocument.DocumentNode.SelectSingleNode("//*[@id=\"_ctl8_viewResult\"]/div/div/div/table//tr[3]/td[2]/strong/text()");

                    txtStudentNameRT.Text = Library.RemoveSpecialCharacter(studentName.InnerText.Trim());
                    txtStudentIdRT.Text = txtStudentIdResultTest.Text;
                    txtClassStableRT.Text = studentStable.InnerText.Trim();

                    List<ResultTest> listResultTest = new List<ResultTest>();
                    foreach (var divTag in htmlDocument.DocumentNode.SelectNodes("//tr[@class='kTableRow'] | //tr[@class='kTableAltRow']"))
                    {
                        ResultTest resultTest = new ResultTest();
                        string courseName = divTag.SelectSingleNode(".//td[2]/a").InnerText.Trim();
                        resultTest.CourseName = Library.LimitWords(courseName, 7, " ...");
                        resultTest.ResultTestAverage = divTag.SelectSingleNode(".//td[12]/strong").InnerText.Trim();
                        listResultTest.Add(resultTest);
                    }
                    lstResultTest.ItemsSource = listResultTest;
                }
                catch (HttpRequestException)
                {
                    MessageBox.Show("Error: HttpRequest");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            else
            {
                MessageBox.Show("Bạn chưa nhập mã sinh viên.");
            }
        }

        private void listResultTest_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            NavigationService.Navigate(new
                Uri("/UserControl/ResultTestDetail.xaml?indexSelected=" + lstResultTest.SelectedIndex +
                "&studentId=" + txtStudentIdResultTest.Text, UriKind.RelativeOrAbsolute));
        }

        private async void btnSearchResultExam(object sender, RoutedEventArgs e)
        {
            if (txtStudentIdRE.Text != "")
            {
                Student student = new Student();
                student.StudentId = txtStudentIdRE.Text;
                string htmlPage = "";
                try
                {
                    using (var client = new HttpClient())
                    {
                        htmlPage = await client.GetStringAsync(Constant.URL_ResultExam + student.StudentId);
                    }

                    HtmlDocument htmlDocument = new HtmlDocument();
                    htmlDocument.LoadHtml(htmlPage);
                    HtmlNode studentName = htmlDocument.DocumentNode.SelectSingleNode("//*[@id=\"_ctl8_viewResult\"]/div/div/div/div/table//tr[1]/td[2]/strong/text()");
                    HtmlNode studentId = htmlDocument.DocumentNode.SelectSingleNode("//*[@id=\"_ctl8_viewResult\"]/div/div/div/div/table//tr[2]/td[2]/strong/text()");
                    HtmlNode studentStable = htmlDocument.DocumentNode.SelectSingleNode("//*[@id=\"_ctl8_viewResult\"]/div/div/div/div/table//tr[3]/td[2]/strong/text()");

                    txtStudentNameRE.Text = Library.RemoveSpecialCharacter(studentName.InnerText.Trim());
                    txtStudentIdREX.Text = txtStudentIdRE.Text;
                    txtClassStableRE.Text = studentStable.InnerText.Trim();

                    List<ResultExamination> listResultExam = new List<ResultExamination>();
                    foreach (var divTag in htmlDocument.DocumentNode.SelectNodes("//tr[@class='kTableRow'] | //tr[@class='kTableAltRow']"))
                    {
                        ResultExamination resultExam = new ResultExamination();
                        resultExam.CourseName = Library.LimitWords(divTag.SelectSingleNode(".//td[3]/a").InnerText.Trim(), 7, " ...");
                        resultExam.ResultExamFirst = divTag.SelectSingleNode(".//td[6]").InnerText.Trim();
                        listResultExam.Add(resultExam);
                    }

                    lstResultExam.ItemsSource = listResultExam;
                }
                catch (HttpRequestException)
                {
                    MessageBox.Show("Error: HttpRequest");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            else
            {
                MessageBox.Show("Bạn chưa nhập mã sinh viên.");
            }
        }

        private void listResultdExam_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            NavigationService.Navigate(new
                Uri("/UserControl/ResultExamDetail.xaml?indexSelected=" + lstResultExam.SelectedIndex +
                "&studentId=" + txtStudentIdRE.Text, UriKind.RelativeOrAbsolute));
        }

        private async void btnSearchPlan_Click(object sender, RoutedEventArgs e)
        {
            if (txtClassIndependentId.Text != "")
            {
                ClassIndependent classIndependent = new ClassIndependent();
                classIndependent.ClassIndependentId = txtClassIndependentId.Text;
                string htmlPage = "";
                try
                {
                    using (var client = new HttpClient())
                    {
                        htmlPage = await client.GetStringAsync(Constant.URL_PlanExam + classIndependent.ClassIndependentId);
                    }
                    HtmlDocument htmlDocument = new HtmlDocument();
                    htmlDocument.LoadHtml(htmlPage);
                    List<PlanExamination> listPlanExam = new List<PlanExamination>();
                    foreach (var divTag in htmlDocument.DocumentNode.SelectNodes("//tr[@class='kTableRow'] | //tr[@class='kTableAltRow']"))
                    {
                        PlanExamination planExam = new PlanExamination();
                        planExam.CourseName = divTag.SelectSingleNode(".//td[3]").InnerText.Trim();
                        planExam.PlanExamDate = divTag.SelectSingleNode(".//td[4]").InnerText.Trim();
                        listPlanExam.Add(planExam);
                    }

                    lstPlanExam.ItemsSource = listPlanExam;
                }
                catch (HttpRequestException)
                {
                    MessageBox.Show("Cannot connect to the internet. Check your internet connection");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            else
            {
                MessageBox.Show("Bạn chưa nhập mã lớp.");
            }
        }

        private void lstPlanExam_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            NavigationService.Navigate(new
                Uri("/UserControl/PlanExamDetail.xaml?indexSelected=" + lstPlanExam.SelectedIndex +
                "&classId=" + txtClassIndependentId.Text, UriKind.RelativeOrAbsolute));
        }

        private async void btnSearchAccumulation_Click(object sender, RoutedEventArgs e)
        {
            if (txtStudentIdAc.Text != "")
            {
                Student student = new Student();
                student.StudentId = txtStudentIdAc.Text;
                string htmlPage = "";
                try
                {
                    using (var client = new HttpClient())
                    {
                        htmlPage = await client.GetStringAsync(Constant.URL_ResultExam + student.StudentId);
                    }

                    HtmlDocument htmlDocument = new HtmlDocument();
                    htmlDocument.LoadHtml(htmlPage);
                    HtmlNode studentName = htmlDocument.DocumentNode.SelectSingleNode("//*[@id=\"_ctl8_viewResult\"]/div/div/div/div/table//tr[1]/td[2]/strong/text()");
                    HtmlNode studentId = htmlDocument.DocumentNode.SelectSingleNode("//*[@id=\"_ctl8_viewResult\"]/div/div/div/div/table//tr[2]/td[2]/strong/text()");
                    HtmlNode studentStable = htmlDocument.DocumentNode.SelectSingleNode("//*[@id=\"_ctl8_viewResult\"]/div/div/div/div/table//tr[3]/td[2]/strong/text()");

                    txtStudentNameAc.Text = Library.RemoveSpecialCharacter(studentName.InnerText.Trim());
                    txtStudentCodeAc.Text = txtStudentIdAc.Text;
                    txtClassStableAc.Text = studentStable.InnerText.Trim();

                    List<ResultExamination> listResultExam = new List<ResultExamination>();
                    foreach (var divTag in htmlDocument.DocumentNode.SelectNodes("//tr[@class='kTableRow'] | //tr[@class='kTableAltRow']"))
                    {
                        ResultExamination resultExam = new ResultExamination();
                        resultExam.CreditNumber = divTag.SelectSingleNode(".//td[4]/text()").InnerText.Trim();
                        resultExam.ResultExamCredit = divTag.SelectSingleNode(".//td[9]/text()").InnerText.Trim();
                        listResultExam.Add(resultExam);
                    }

                    double tongTC = 0;
                    double tongdiemTC = 0;
                    double tichluy = 0;
                    double demA = 0, demB = 0, demC = 0, demD = 0;
                    foreach (ResultExamination items in listResultExam)
                    {
                        if (items.ResultExamCredit != "F" && items.ResultExamCredit != "I")
                        {
                            tongTC += Int32.Parse(items.CreditNumber);
                        }
                        if (items.ResultExamCredit == "A")
                        {
                            tongdiemTC += int.Parse(items.CreditNumber) * 4;
                            demA++;
                        }
                        else if (items.ResultExamCredit == "B")
                        {
                            tongdiemTC += int.Parse(items.CreditNumber) * 3;
                            demB++;
                        }
                        else if (items.ResultExamCredit == "C")
                        {
                            tongdiemTC += int.Parse(items.CreditNumber) * 2;
                            demC++;
                        }
                        else if (items.ResultExamCredit == "D")
                        {
                            tongdiemTC += int.Parse(items.CreditNumber) * 1;
                            demD++;
                        }
                        else
                        {
                            tongdiemTC += int.Parse(items.CreditNumber) * 0;
                        }



                        //switch (items.ResultExamCredit)
                        //{
                        //    case "A":
                        //        diemtc = 4;
                        //        break;
                        //    case "B":
                        //        diemtc = 3;
                        //        break;
                        //    case "C":
                        //        diemtc = 2;
                        //        break;
                        //    case "D":
                        //        diemtc = 1;
                        //        break;
                        //}
                        //double tichluymon = int.Parse(items.CreditNumber) * diemtc;


                    }

                    tichluy = Math.Round(tongdiemTC / tongTC, 2);
                    tichLuy.Text = tichluy.ToString();
                    tongTinChi.Text = Library.RemoveSpecialCharacter(tongTC.ToString());

                    txtdiemA.Text = "Điểm A : " + demA.ToString();
                    txtdiemB.Text = "Điểm B : " + demB.ToString();
                    txtdiemC.Text = "Điểm C : " + demC.ToString();
                    txtdiemD.Text = "Điểm D : " + demD.ToString();
                }
                catch (HttpRequestException)
                {
                    MessageBox.Show("Error: HttpRequest");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            else
            {
                MessageBox.Show("Bạn chưa nhập mã sinh viên.");
            }
        }

    }
}